<template>
  <el-dialog
    :model-value="appointmentVisible"
    :title="appointmentTitle"
    width="70%"
    @close="handleClose"
  >
    <el-form :model="queryForm" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="所需配件数量" prop="total">
        <el-input v-model="queryForm.total" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { modify } from '../../../api/inventory'
import { save } from '../../../api/maintainAcc'

const queryForm = ref({
  total: ''
})

const form = ref({
  maintainId: '',
  accId: '',
  accCount: ''
})

const appointmentVisible = ref(false)
const appointmentTitle = ref('')

const emits = defineEmits(['update:modelValue', 'query'])

// 关闭
function handleClose() {
  emits('update:modelValue', false)
}

const pas = ref({})

// 确认
async function handleConfirm() {
  // 修改选择的配件查询库存是否足够
  if (queryForm.value.accessories.total >= queryForm.value.total) {
    queryForm.value.accessories.total = (queryForm.value.accessories.total - queryForm.value.total)
    pas.value = queryForm.value
    // 赋值给相应的值
    form.value.accCount = queryForm.value.total
    form.value.accId = queryForm.value.accessoriesId
    await modify(pas.value) // 修改
    await save(form.value) // 新增项目基础配件
    ElMessage({
      message: '选择配件成功',
      type: 'success'
    })
    // 上层主键获取信息
    emits('query')
    // 关闭
    handleClose()
  } else {
    ElMessage({
      message: '库存不足！！',
      type: 'info'
    })
  }
}

const props = defineProps({
  // 标题
  appointmentTitle: {
    type: String,
    default: '',
    required: true
  },
  // 编辑行数据
  appointmentRowValue: {
    type: Object,
    default: () => {}
  },
  // 编辑行数据
  appointmentRowValues: {
    type: Object,
    default: () => {}
  }
})
// 监听props.dialogRowValue值改变
watch(
  () => props.appointmentRowValue,
  () => {
    queryForm.value = props.appointmentRowValue
  },
  { deep: true, immediate: true }
)
// 监听props.dialogRowValue值改变
watch(
  () => props.appointmentRowValues,
  () => {
    form.value.maintainId = props.appointmentRowValues
  },
  { deep: true, immediate: true }
)

</script>

<style class="scss" scoped>
::v-deep .el-input__prefix-inner {
  align-items: center;
}
</style>
